package com.merry.sb.aop.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibProxyExample {

    static class Service {
        public void execute() {
            System.out.println("Service method executed");
        }
    }

    static class ServiceLogInterceptor implements MethodInterceptor {
        @Override
        public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            System.out.println("Before method execution");
            Object result = proxy.invokeSuper(obj, args);
            System.out.println("After method execution");
            return result;
        }
    }

    public static void main(String[] args) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(Service.class);
        enhancer.setCallback(new ServiceLogInterceptor());

        Service proxyService = (Service) enhancer.create();
        proxyService.execute();
    }
}
